<?php
namespace control;
/*
*培训记录类
*/

class trainingRecordClass extends adIndexClass
{
    private const page = 'trainingRecord';
    private const table = 'training_record';
    private const title = '培训记录';
    public array $stateOption = ['草稿', '审核中', '已通过'];
    /**
     * 员工页卡培训记录
     *
     * @return bool|string
     */
    public function trainRecord(): bool|string
    {
        $html =
            hidden(array("name" => "targetId", "value" => $this->get('id'))) .
            select(array("name" => "type", "title" => L('trainingPlan.table.trainingType'), "option" => explode('，', para('trainingType')))) .
            text(array("name" => "project", "title" => L('trainingPlan.table.trainingProject'))) .
            text(array("name" => "address", "title" => L('trainingPlan.table.trainingAddr'))) .
            text(array("name" => "createTime",'class'=>'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('recruitment.table.createTime')."-".L('recruitment.table.createTime')));
        //返回
        $json['html'] = $this->search($html);
        return json_encode($json, 320);
    }

    public function trainRecordSearch(): bool|string
    {
        $id = $this->post('targetId');
        $and = " and member like '%$id%'";
        //like查询数组
        $like = array(
            "project" => $this->post('project'),//培训项目
            "address" => $this->post('address'),//培训地点
        );
        //全等查询数组
        $equal = array(
            'state'=>'已通过',
            "type" => $this->post('type'),//培训类别
        );
        if ($this->post('createTime')) {
            $and.=self::timeComparison($this->post('createTime'));
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //获取表头
        $tr[] = array('', L('trainingPlan.table.trainingType'), L('trainingPlan.table.trainingProject'), L('trainingPlan.table.trainingTime'), L('trainingPlan.table.trainingAddr'), L('trainingPlan.table.speaker'), L('trainingPlan.table.method'), L('trainingPlan.table.joinFact'), L('trainingPlan.table.state'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => L('trainingPlan.table.record'), "click" => "newIframe('" . L('trainingPlan.table.record'). "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $array['trainingTime'] = str_replace('~', '至', $array['trainingTime']);
            $num = $array['member'] ? count(explode(',', $array['member'])) : 0;
            $tr[] = array($this->dominate($dominate), $array['type'], $array['project'], $array['trainingTime'], $array['address'], $array['speaker'], $array['assessType'], $num, $array['state']);
        }
        //返回
        $json['html'] = $page['hint'] ."<form name='trainRecordForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            select(array("name" => "type", "title" => L('trainingPlan.table.trainingType'), "option" => explode('，', para('trainingType')))) .
            text(array("name" => "project", "title" => L('trainingPlan.table.trainingProject'))) .
            text(array("name" => "address", "title" => L('trainingPlan.table.trainingAddr'))) .
            text(array("name" => "createTime",'class'=>'width200',  'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('recruitment.table.createTime')."-".L('recruitment.table.createTime'))) .
            select(array("name" => "state", "title" => L('trainingPlan.table.state'), "option" => $this->stateOption));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "project" => $this->post('project'),//培训项目
            "address" => $this->post('address'),//培训地点
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "type" => $this->post('type'),//培训类别

        );
        $and = "";
        if ($this->post('createTime')) {
            $and.=self::timeComparison($this->post('createTime'));
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('trainingPlan.table.trainingType'), L('trainingPlan.table.trainingProject'), L('trainingPlan.table.trainingTime'), L('trainingPlan.table.trainingAddr'), L('trainingPlan.table.speaker'), L('trainingPlan.table.method'), L('trainingPlan.table.joinFact'), L('trainingPlan.table.state'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('trainingPlan.table.record'), "click" => "newIframe('" . L('trainingPlan.table.record') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $array['trainingTime'] = str_replace('~', '至', $array['trainingTime']);
            $num = $array['member'] ? count(explode(',', $array['member'])) : 0;
            $tr[] = array($this->dominate($dominate), $array['type'], $array['project'], $array['trainingTime'], $array['address'], $array['speaker'], $array['assessType'], $num, $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('trainingPlan.table.record') . "','" . $url . "&fun=edit')\" class='spanButton'>".L('recruitment.table.add')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('recruitment.table.del')."</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
	            "name"  => L('public.submit'),
                "type" => "点击事件",
                "cla" => $this->get('cla'),
                "fun" => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
                "post" => ["id" => $this->get('id')],
                'style' => 'li-btn-blue-bg',
            ];
	        $button[]  = [
		        "name"  => L('public.saveDraft'),
		        "type"  => "点击事件",
		        "cla"   => $this->get('cla'),
		        "fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
		        "post"  => ["id" => $this->get('id')],
		        'style' => 'li-btn-green-bg',
	        ];
        }
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button)
                ],
                [
                    must . L('trainingPlan.table.trainingProject')."：" => text(array('name' => 'project', 'class' => 'text', 'value' => $info['project'])),
                    must . L('trainingPlan.table.trainingTime')."：" => text(["name" => "trainingTime", 'class' => 'long', 'laydate' => ['range' => '~', 'type' => 'datetime'], "value" => $info['trainingTime']]),
                ],
                [
                    must . L('trainingPlan.table.hours')."：" => text(array('name' => 'hour', 'class' => 'text', 'unit' => 'h', 'value' => $info['hour'])),
                    must . L('trainingPlan.table.trainingAddr')."：" => text(array('name' => 'address', 'class' => 'text', 'value' => $info['address'])),
                ],
                [
                    L('trainingPlan.table.trainingType')."：" => select(array('name' => 'type', 'title' => L('trainingPlan.table.trainingType'), 'class' => 'select', 'value' => $info['type'], 'option' => explode('，', para('trainingType')))),
                    L('trainingPlan.table.speaker')."：" => text(array('name' => 'host', 'class' => 'text', 'value' => $info['host'])),
                ],
                [
                    L('trainingPlan.table.method')."：" => select(array('name' => 'assessType', 'title' => L('trainingPlan.table.method'), 'class' => 'select', 'value' => $info['assessType'], 'option' => explode('，', para('trainingExamine')))),
                    L('trainingPlan.table.speaker')."：" => text(array('name' => 'speaker', 'class' => 'text', 'value' => $info['speaker'])),
                ],
                [
                    L('trainingPlan.table.overview')."：" => textarea(array('name' => 'content', 'class' => 'textarea', 'value' => $info['content'])),
                ],
                [
                    L('trainingPlan.table.members')."：" => componentClass::staffSelector($info['selector'])
                ],
                [
                    "<div><span class='small-title'>".L('staffProfiles.table.enclosure')."</span></div>" . fileUploadClass::addFileComponent($info['id'], '培训记录', self::page, self::page . 'EditForm'),
                ],
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $info['id'] ?:$id)),
            'button' => ' ',
        ]);
        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id = $this->post('id')?:suiji();
        //附件
        $fileIdArr = $this->post('fileId');
        $field = [
            'project' => $this->post('project'),
            'trainingTime' => $this->post('trainingTime'),
            'hour' => $this->post('hour'),
            'address' => $this->post('address'),
            'type' => $this->post('type'),
            'host' => $this->post('host'),
            'speaker' => $this->post('speaker'),
            'assessType' => $this->post('assessType'),
            'selector'       => $this->post('staff')[0]??'',//员工选择器
            'content' => $this->post('content')
        ];
        $field['member'] = implode(',',componentClass::returnStaffId($field['selector']));
        $annotation = [
            'project' => L('trainingPlan.table.trainingProject'),
            'trainingTime' => L('trainingPlan.table.trainingTime'),
            'address' => L('trainingPlan.table.trainingAddr'),
        ];
        $rules = [
            'project' => 'required',
            'trainingTime' => 'required',
            'address' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('trainingPlan.table.edit_permission');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'PXJL' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $text = str_replace(['{{staffName}}','{{projectName}}','{{id}}'],[$this->control['name'],$field['project'],$id],L('trainingPlan.table.record_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => L('recruitment.table.commitAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '培训记录',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" =>L('recruitment.table.audit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => L('recruitment.table.addAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" =>L('recruitment.table.audit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('recruitment.table.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('recruitment.table.no_record');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            //审核按钮
            $button = $this->auditButton($info);
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.edit'),
                    "type" => "顶部页卡",
                    "title" => L('recruitment.table.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],

                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" =>L('trainingPlan.table.uploadForm'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "uploadFile",
                    "post" => ["id" => $info['id']],
                ];
            }
            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($info['id'], '培训记录');
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        L('trainingPlan.table.trainingType') => $info['type'],
                        L('trainingPlan.table.trainingProject') => $info['project'],
                        L('trainingPlan.table.trainingTime') => str_replace('~', '至', $info['trainingTime']),
                    ),
                    array(
                        L('trainingPlan.table.hours')."(h)" => $info['hour'],
                        L('trainingPlan.table.trainingAddr') => $info['address'],
                        L('trainingPlan.table.speaker') => $info['host'],
                    ),
                    array(
                        L('trainingPlan.table.speaker') => $info['speaker'],
                        L('trainingPlan.table.method') => $info['assessType'],
                    ),
                    array(
                        L('trainingPlan.table.overview') => $info['content'],
                    ),
                    array(
                         L('trainingPlan.table.members') =>componentClass::showSelector($info['selector']),
                    ),
                ),
                L('staffProfiles.table.enclosure') => array(
                    array(
                        $fileCollection
                    ),
                ),
                L('trainingPlan.table.trainForm') => array(
                    array(
                        fileUploadClass::showFile($info['id'], '培训签到表')
                    ),
                ),
                L('staffProfiles.detail.system_info') => array(

                    array(
                        L('trainingPlan.table.orderNo') => $info['orderNo'],
                        L('department.table.creator') => self::findStaff($info['stid']),
                        L('department.table.creatTime') => $info['time'],
                    ),
                    array(
                        L('department.table.updateTime') => $info['updateTime'],
                        L('trainingPlan.table.state') => $info['state'],
                    ),
                ),
                L('recruitment.table.flow') => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function uploadFile()
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    fileUploadClass::addFileComponent($this->post('id'), L('trainingPlan.table.trainForm'), self::page, 'trainingRecordUploadFileForm')
                ),
            )
        ));
        //返回
        return $this->layer(array("title" => L('trainingPlan.table.uploadForm'), "height" => 300, "width" => 900, "html" => $html));
    }

    public function uploadFileEdit(): bool|string
    {
        $fileIdArr = $this->post('fileId')?:[];
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('trainingPlan.table.edit_permission');
        } elseif (empty($id)) {
            $json['warn'] = L('staffProfiles.talentPool.no_id');
        } else {
            $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            if (in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = 2;
                $_SESSION['warn'] = L('trainingPlan.table.upload_success');
            } else {
                $json['warn'] = L('trainingPlan.table.upload_failed');
            }
        }
        return json_encode($json, 320);
    }
    /**
     * 获取参训人员姓名
     */
    public function findMember($member): string
    {
        $result = '';
        if ($member) {
            $memberArr = explode(',', $member);
            foreach ($memberArr as $stid) {
                $name = self::findStaff($stid);
                $result .= "<span style='padding: 2px 10px;background-color: #F2F2F2;margin-left: 10px'>{$name}</span>";
            }
        }
        return $result;
    }



    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('trainingPlan.table.delRecord');
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'],[$msg],L('recruitment.table.msg'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_per');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn =  L('recruitment.table.draft');
                } else {
                    //删除audit表记录
                    delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                    $all = find(array('table'=>'file','where'=>"targetId = '$id'"));
                    foreach ($all['array'] as $val){
                        fileDelete($val['src']);
                        delete(array("table" =>'file', "where" => " id = '$val[id]' "));
                    }
                    //删除待办事项
                    delete(array("table" => "backlog","where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message","where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn =  L('recruitment.table.del_suc');
                    $x++;
                }
                $text .= str_replace(['{{projectName}}','{{id}}'],[$info['project'],$info['id']],L('trainingPlan.table.record_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('trainingPlan.table.record_del_log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('trainingPlan.table.record_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }




}

